//
//  PingLeiViewController.m
//  Wujin
//
//  Created by cz on 2016/12/10.
//  Copyright © 2016年 dong. All rights reserved.
//

#import "PingLeiViewController.h"
#import "PingLeiSearchView.h"
#import "SearchGoodsViewController.h"
#import "PinLeiTableViewCell.h"
#import "CategoryModel.h"
#import "PinLeiCollectionCell.h"

@interface PingLeiViewController ()<PingLeiSearchViewDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UIGestureRecognizerDelegate>

@property (nonatomic,strong) PingLeiSearchView *searchView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) NSMutableArray *categoryList;

@property (nonatomic,strong) NSMutableArray *childCategory;

@property (nonatomic,strong) CategoryModel *categoryModel;

@property (nonatomic,strong) UIButton *coverButton;
@property (nonatomic,strong) UILabel *tipLabel;
@end

@implementation PingLeiViewController

- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] init];
        _tipLabel.frame = _collectionView.bounds;
        _tipLabel.text = @"请选择一个分类^_^";
        _tipLabel.font = [UIFont systemFontOfSize:15];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.textColor = rgb(253, 199, 30);
    }
    return _tipLabel;
}

- (NSMutableArray *)childCategory {
    if (!_childCategory) {
        _childCategory = [NSMutableArray array];
    }
    return _childCategory;
}

- (NSMutableArray *)categoryList {
    if (!_categoryList) {
        _categoryList = [NSMutableArray array];
    }
    return _categoryList;
}

//懒加载tableView
- (UITableView *)tableView {
    
    if (!_tableView) {
        
        CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame) + self.searchView.frame.size.height;
        CGFloat height = SCREENBOUNDS.height - y - self.tabBarController.tabBar.frame.size.height;
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, y ,SCREENBOUNDS.width * 0.3, height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = rgb(245, 245, 249);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.bounces = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
//懒加载collectionView
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(100, 100);
        
        self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width,self.tableView.frame.origin.y, SCREENBOUNDS.width - self.tableView.frame.size.width, self.tableView.frame.size.height) collectionViewLayout:layout];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.backgroundColor = rgb(240, 240, 240);
        
        //注册cell
                [self.collectionView registerNib:[UINib nibWithNibName:@"PinLeiCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"pinleiCellId"];
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置UI
    [self setupUI];
}

- (void)setupUI {
    //设置搜索框
    [self setUpSearchBar];
    //设置TableView
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.collectionView];
    
    [self.collectionView addSubview:self.tipLabel];
    
    [self.tableView reloadData];
    //加载以及分类列表
    [self loadCategoryData];
    
}

#pragma mark --- tableView的代理与数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.categoryList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *reuseId = @"tableViewCell";
    PinLeiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"PinLeiTableViewCell" owner:nil options:nil] lastObject];
    }        
    cell.categoryModel = self.categoryList[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    self.categoryModel = self.categoryList[indexPath.row];
    self.childCategory = nil;
    for (NSDictionary *dict in self.categoryModel.child) {
        Child *child = [Child mj_objectWithKeyValues:dict];
        [self.childCategory addObject:child];
    }
    
    [self.collectionView reloadData];
    
    if (self.tipLabel) {
        [self.tipLabel removeFromSuperview];
        
        if (self.childCategory.count == 0) {
            self.tipLabel.text = @"抱歉,该分类暂无商品^_^";
            [self.collectionView addSubview:self.tipLabel];
        }
    }
}


#pragma mark -- collectionView的代理与数据源方法
//组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}
//行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.categoryModel.child.count;
    
}

//设置每个cell的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(10, 10, 10, 10);
    
}

//设置每个item的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat width = (self.collectionView.frame.size.width - 40) * 0.5;
    
    return CGSizeMake(width, width * 0.3);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PinLeiCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pinleiCellId" forIndexPath:indexPath];
    
    cell.child = self.childCategory[indexPath.row];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PinLeiCollectionCell *cell = (PinLeiCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    [self collectionViewCellDidSelected:cell.child.Id];
}


/**
 请求分类列表数据
 */
- (void)loadCategoryData {
    
    NSMutableDictionary *dict = nil;
    NSString *url = F(@"%@Index/getCategory", BASEURL);
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([responseObject[@"flag"] intValue] == 1) {
                
                for (NSDictionary *dict in responseObject[@"data"]) {
                    
                    CategoryModel *model  = [CategoryModel mj_objectWithKeyValues:dict];
                    
                    [CategoryModel mj_setupObjectClassInArray:^NSDictionary *{
                        return @{ @"child":@"Child"};
                    }];
                    [self.categoryList addObject:model];                    
                }
                
                [self.tableView reloadData];
                [self.collectionView reloadData];
            }else{
                DLog(@"没有请求到数据");
                [MRHud showWithFailure:@"您的网络不给力"];
            }
        }
    }];    
}


//设置搜索条
- (void)setUpSearchBar{
    PingLeiSearchView *searchView = [PingLeiSearchView setupPingLeiSearchView];
    searchView.delegate = self;
    searchView.PLTextField.delegate = self;
    searchView.frame = CGRectMake(0, 64, SCREENBOUNDS.width, 44);
    _searchView = searchView;
    [self.view addSubview:searchView];
}

- (void)searchBtnDidClicked {
    DLog(@"搜索");
    [self handleSearchBar];
}
//键盘上的确定按钮的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self handleSearchBar];
    return YES;
}
//输入框一开始输入调用
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    
    return YES;
}

//隐藏键盘
- (void)hideKeyboard:(UITapGestureRecognizer *) tap{
    
    [self.searchView endEditing:YES];
    [self.view removeGestureRecognizer:tap];
}

/**
 处理搜索条，进行相应的功能
 */
- (void)handleSearchBar {
    if ([_searchView.PLTextField.text isEqualToString:@""]) {
        DLog(@"搜索内容不能为空");
        [MRHud show];
        [MRHud dismissWithFailure:@"请输入商品名称"];
    }else{
        DLog(@"%@",_searchView.PLTextField.text);
        SearchGoodsViewController *searchVc = [[SearchGoodsViewController alloc] init];
        searchVc.keyword = self.searchView.PLTextField.text;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchVc];
        [self presentViewController:nav animated:YES completion:nil];
    }
}


/**
 点击collectionViewCell调用
 */
- (void)collectionViewCellDidSelected:(NSString *) keyword{
    SearchGoodsViewController *searchVc = [[SearchGoodsViewController alloc] init];
    searchVc.gc_id = keyword;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchVc];
    [self presentViewController:nav animated:YES completion:nil];
}

@end
